package org.swust.sysmonitorapp.service;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.swust.sysmonitorapp.amqp.AmqpClient;
import org.swust.sysmonitorapp.amqp.AmqpClientOptions;
import org.swust.sysmonitorapp.config.AmqpProperties;
import org.swust.sysmonitorapp.entity.HealthData;
import org.swust.sysmonitorapp.service.handler.DevicePropertyHandler;
import org.swust.sysmonitorapp.service.handler.DeviceStatusHandler;
import org.swust.sysmonitorapp.service.handler.MessageHandler;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.JMSException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class AmqpConsumer {
    private final AmqpClient client;
    private final AmqpProperties properties;
//    private final IHealthDataService healthDataService;
//    private final IDeviceStatusService deviceStatusService;
    private final ObjectMapper objectMapper;

    //添加一个分发器，分别对不同的订阅数据进行处理
    private final Map<String, MessageHandler> handlerMap = new HashMap<>();

    public AmqpConsumer(AmqpProperties properties, IHealthDataService healthDataService, IDeviceStatusService deviceStatusService, IDeviceStatusService deviceStatusService1, ObjectMapper objectMapper) {
        this.properties = properties;
//        this.healthDataService = healthDataService;
//        this.deviceStatusService = deviceStatusService;
        this.objectMapper = objectMapper;

        AmqpClientOptions options = AmqpClientOptions.builder()
                .host(properties.getHost())
                .port(properties.getPort())
                .accessKey(properties.getAccessKey())
                .accessCode(properties.getAccessCode())
                .queuePrefetch(properties.getPrefetch())
                .build();
        this.client = new AmqpClient(options);
        handlerMap.put("device.property", new DevicePropertyHandler(healthDataService));
        handlerMap.put("device.status", new DeviceStatusHandler(deviceStatusService));
    }

    @PostConstruct
    public void start() throws Exception {
        client.initialize();
        client.newConsumer(properties.getQueue()).setMessageListener(message -> {
            try {
                String body = message.getBody(String.class);
                processAndSave(body);
            } catch (JMSException e) {
                log.error("Failed to parse message body", e);
            }
        });
        log.info("AMQP consumer started successfully");
    }

    private void processAndSave(String jsonData) {
        try {
            ObjectMapper customMapper = objectMapper.copy();
            customMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

            JsonNode root = customMapper.readTree(jsonData);

            // 展示 JSON 数据
            Object jsonObject = customMapper.readValue(jsonData, Object.class);
            String prettyJson = customMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
            log.info("收到的 JSON 数据:\n{}", prettyJson);

            // 提取 resource & event
            String resource = root.path("resource").asText();
            String event = root.path("event").asText();
            log.info("resource: {}, event: {}", resource, event);

            // 根据 resource 分发
            MessageHandler handler = handlerMap.get(resource);
            if (handler != null) {
                handler.handle(root);
            } else {
                log.warn("没有找到对应的处理器，resource={}", resource);
            }

        } catch (Exception e) {
            log.error("处理并保存消息失败", e);
        }
    }


    @PreDestroy
    public void stop() {
        client.close();
        log.info("AMQP consumer stopped");
    }
}